﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using System.Drawing;

namespace Ymatou.CommonService
{
    public static class Uploads
    {
        private static string FileSiteValidKey
        {
            get { return "&bhkey=bh051986943966"; }
        }


        private static string FileSite
        {
            get
            {
                if (ConfigurationManager.AppSettings["FileSite"] != null)
                {
                    return ConfigurationManager.AppSettings["FileSite"];
                }
                else
                {
                    return "http://file.ymatou.com";
                }
            }

        }

        private static string ImageSite
        {
            get
            {
                if (ConfigurationManager.AppSettings["ImageSiteUrl"] != null)
                {
                    return ConfigurationManager.AppSettings["ImageSiteUrl"];
                }
                else
                {
                    return "http://jk3.img.ymatou.com";
                }
            }
        }


        /// <summary>
        /// 保存图片到uploads对应的img目录下
        /// </summary>
        /// <param name="postedFile">保存的图片文件</param>
        /// <param name="picType">图片类型</param>
        /// <param name="savedFileName">保存的图片文件名</param>
        /// <param name="error">保存出错时的异常信息</param>
        /// <returns>保存是否成功</returns>
        public static bool UpLoadPicFile(HttpPostedFile postedFile, string picType, string savedFileName, out string error)
        {
            bool status = false;
            error = "";
            string fileExt = Path.GetExtension(postedFile.FileName);
            if (fileExt != null)
            {
                fileExt = fileExt.ToLower();
            }
            if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".png")
            {
                string dirPath = System.Web.HttpContext.Current.Server.MapPath("/uploads") + "/img/" + picType + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day;
                DirectoryInfo upDir = new DirectoryInfo(dirPath);
                if (!upDir.Exists)
                {
                    upDir.Create();
                }
                try
                {
                    postedFile.SaveAs(dirPath + "/" + savedFileName);
                    status = true;
                }
                catch (Exception ex)
                {
                    error = "图片存储错误。" + ex.Message.ToString();
                }
            }
            return status;
        }
        /// <summary>
        /// 保存图片到uploads对应的img目录下
        /// </summary>
        /// <param name="postedFile">保存的图片文件</param>
        /// <param name="picType">图片类型</param>
        /// <param name="savedFileName">保存的图片文件名</param>
        /// <param name="picPath">The pic path.</param>
        /// <param name="error">保存出错时的异常信息</param>
        /// <returns>保存是否成功</returns>
        public static bool UpLoadPicFile(HttpPostedFile postedFile, string picType, string savedFileName, out string picPath, out string error)
        {
            picPath = string.Empty;
            bool status = false;
            error = "";
            string fileExt = Path.GetExtension(postedFile.FileName);
            if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".JPG" || fileExt == ".GIF" || fileExt == ".BMP" || fileExt == ".png" || fileExt == ".PNG")
            {
                string dirPath = HttpContext.Current.Server.MapPath("/uploads") + "/img/" + picType + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day;
                picPath = string.Format("/uploads/img/{0}/{1}/{2}/{3}", picType, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                DirectoryInfo upDir = new DirectoryInfo(dirPath);
                if (!upDir.Exists)
                {
                    upDir.Create();
                }
                try
                {
                    postedFile.SaveAs(dirPath + "/" + savedFileName);
                    status = true;
                }
                catch (Exception ex)
                {
                    error = "图片存储错误。" + ex.Message;
                }
            }
            return status;
        }

        /// <summary>
        /// 此方法用于编辑器中的上传图片功能
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="picType"></param>
        /// <param name="savedFileName"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static string UpLoadDescPicFile(HttpPostedFileBase postedFile, string picType, string savedFileName, out string error)
        {
            string result = "";
            error = "";
            string fileExt = Path.GetExtension(postedFile.FileName).ToLower();
            if (fileExt != null)
            {
                fileExt = fileExt.ToLower();
            }
            if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".png" || fileExt == ".jpeg")
            {
                byte[] bt = new byte[postedFile.ContentLength];
                try
                {
                    postedFile.InputStream.Read(bt, 0, bt.Length);
                    postedFile.InputStream.Close();
                    string url = ImageSite + "/BHUploadPicture.ashx?picname=" + savedFileName + "&type=" + picType + "&bhkey=bh051985613966";
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.KeepAlive = true;
                    Stream requestStream = req.GetRequestStream();
                    requestStream.Write(bt, 0, bt.Length);
                    requestStream.Close();
                    using (WebResponse rep = req.GetResponse())
                    {
                        using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.Default))
                        {
                            result = sr.ReadToEnd();
                        }
                    }

                    req.Abort();
                }
                catch (Exception ex)
                {
                    error = ex.Message.ToString();
                }
            }
            else
            {
                error = "上传图片格式错误。";
            }
            return result;
        }

        /// <summary>
        /// 保存图片到uploads对应的img目录下
        /// </summary>
        /// <param name="postedFile">保存的图片文件</param>
        /// <param name="picType">图片类型</param>
        /// <param name="savedFileName">保存的图片文件名</param>
        /// <param name="error">保存出错时的异常信息</param>
        /// <returns>保存是否成功</returns>
        public static string UpLoadPicFile(HttpPostedFileBase postedFile, string picType, string savedFileName, out string error)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory;
            string result = "";
            error = "";
            string fileExt = Path.GetExtension(postedFile.FileName).ToLower();
            if (fileExt != null)
            {
                fileExt = fileExt.ToLower();
            }
            if (postedFile.ContentLength > 500 * 1024)
            {
                error = "error500";
                return result;
            }
            if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".png" || fileExt == ".jpeg")
            {
                byte[] bt = new byte[postedFile.ContentLength];
                try
                {
                    postedFile.InputStream.Read(bt, 0, bt.Length);
                    System.Drawing.Image image = System.Drawing.Image.FromStream(postedFile.InputStream);
                    if (image.Width < 800 || image.Height < 800)
                    {
                        return "error800";
                    }
                    postedFile.InputStream.Close();
                    string url = ImageSite + "/BHUploadPicture.ashx?picname=" + savedFileName + "&type=" + picType + "&bhkey=bh051985613966";
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.KeepAlive = true;
                    Stream requestStream = req.GetRequestStream();
                    requestStream.Write(bt, 0, bt.Length);
                    requestStream.Close();
                    using (WebResponse rep = req.GetResponse())
                    {
                        using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.Default))
                        {
                            result = sr.ReadToEnd();
                        }
                    }

                    req.Abort();
                }
                catch (Exception ex)
                {
                    error = ex.Message.ToString();
                }
            }
            else
            {
                error = "上传图片格式错误。";
            }
            return result;
        }

        public static string UpLoadPicFile(byte[] fileBytes, string picType, string savedFileName, out string error)
        {
            string result = "";
            error = "";

            string fileExt = Path.GetExtension(savedFileName);
            if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".JPG" || fileExt == ".GIF" || fileExt == ".BMP" || fileExt == ".png" || fileExt == ".PNG")
            {
                try
                {
                    string url = ImageSite + "/BHUploadPicture.ashx?picname=" + savedFileName + "&type=" + picType + "&bhkey=bh051985613966";
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    Stream requestStream = req.GetRequestStream();
                    requestStream.Write(fileBytes, 0, fileBytes.Length);
                    requestStream.Close();
                    using (WebResponse rep = req.GetResponse())
                    {
                        using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.Default))
                        {
                            result = sr.ReadToEnd();
                        }
                    }

                    req.Abort();
                }
                catch (Exception ex)
                {
                    error = ex.Message.ToString();
                }
            }
            else
            {
                error = "上传图片格式错误。";
            }
            return result;
        }

        /// <summary>
        /// 保存图片到uploads对应的img目录下
        /// </summary>
        /// <param name="postedFile">保存的图片文件</param>
        /// <param name="picType">图片类型</param>
        /// <param name="savedFileName">保存的图片文件名</param>
        /// <param name="error">保存出错时的异常信息</param>
        /// <returns>保存是否成功</returns>
        public static string UpLoadPicFile(Stream postedFile, string picType, string savedFileName, out string error)
        {
            string result = "";
            error = "";
            string fileExt = Path.GetExtension(savedFileName);
            if (fileExt != null)
            {
                fileExt = fileExt.ToLower();
            }
            if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".png")
            {
               
                try
                {
                    
                    string url = ImageSite + "/BHUploadPicture.ashx?picname=" + savedFileName + "&type=" + picType + "&bhkey=bh051985613966";
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    Stream requestStream = req.GetRequestStream();

                    byte[] bt = new byte[postedFile.Length];
                    postedFile.Read(bt, 0, bt.Length);
                    requestStream.Write(bt, 0, bt.Length);
                    postedFile.Close();
                    requestStream.Close();
                    using (WebResponse rep = req.GetResponse())
                    {
                        using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.Default))
                        {
                            result = sr.ReadToEnd();
                        }
                    }

                    req.Abort();
                }
                catch (Exception ex)
                {
                    error = ex.Message.ToString();
                }
            }
            else
            {
                error = "上传图片格式错误。";
            }
            return result;
        }

        

        public static string DownLoadPicFile(string picUrl, string picType, string savedFileName, out string error)
        {
            string result = "";
            error = "";

            string fileExt = Path.GetExtension(savedFileName);
            if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".JPG" || fileExt == ".GIF" || fileExt == ".BMP" || fileExt == ".png" || fileExt == ".PNG")
            {
                try
                {
                    string url = ImageSite + "/BHDownLoadPicture.ashx?picname=" + savedFileName + "&type=" + picType + "&bhkey=bh051985613966" + "&picurl=" + HttpUtility.UrlEncode(picUrl);
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = "GET";
                    //req.ContentType = "application/x-www-form-urlencoded";
                    using (WebResponse rep = req.GetResponse())
                    {
                        using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.Default))
                        {
                            
                            result = sr.ReadToEnd();
                        }
                    }

                    req.Abort();
                }
                catch (Exception ex)
                {
                    error = ex.Message.ToString();
                }
            }
            else
            {
                error = "上传图片格式错误。";
            }
            return result;
        }

        #region 图片处理接口
        public static string ImageGetPreviewPic(string type, string name, int maxWidth, int maxHeight, out string error, out int width, out int height, string source = "Source", string dest = "Preview")
        {
            string result = "";
            error = "";
            width = 0;
            height = 0;
            try
            {
                string url = ImageSite + "/ImageTool/GetPreviewPic?type=" + type + "&name=" +
                                 name + FileSiteValidKey + "&maxWidth=" + maxWidth + "&maxHeight=" + maxHeight
                                 + "&source=" + source + "&dest=" + dest;


                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                using (WebResponse rep = req.GetResponse())
                {
                    using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                req.Abort();
            }
            catch (Exception e)
            {
                error = e.Message;
                return "";
            }

            string errorFlag = "Error:";

            //返回有错误
            if (result.StartsWith(errorFlag))
            {
                error = result.Substring(errorFlag.Length - 1);
                result = "";
            }
            else
            {
                string param = result.Substring(result.LastIndexOf("#") + 1);
                int.TryParse(param.Split('&')[0], out width);
                int.TryParse(param.Split('&')[1], out height);
            }

            return result.Substring(0, result.LastIndexOf("#"));
        }



        public static string ImageAddWaterMark(string type, string name, string fmark, out string error, string source = "Source", string dest = "WarterMaked")
        {
            string result = "";
            error = "";
            try
            {
                string url = ImageSite + "/ImageTool/AddWaterMark?type=" + type + "&name=" +
                                 name + FileSiteValidKey + "&fmark=" + fmark
                                 + "&source=" + source + "&dest=" + dest;


                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                using (WebResponse rep = req.GetResponse())
                {
                    using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                req.Abort();
            }
            catch (Exception e)
            {
                error = e.Message;
                return "";
            }

            string errorFlag = "Error:";

            //返回有错误
            if (result.StartsWith(errorFlag))
            {
                error = result.Substring(errorFlag.Length - 1);
                result = "";
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="name"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="widthZipRate"></param>
        /// <param name="heightZipRate"></param>
        /// <param name="mappedSource">源图片</param>
        /// <param name="error"></param>
        /// <param name="source">现在处理的预览图</param>
        /// <param name="dest">处理后图片的位置</param>
        /// <returns></returns>
        public static string ImageResizePic(string type, string name, float x, float y, float width, float height,
                        float widthZipRate, float heightZipRate, string mappedSource, int targetWidth, int targetHeight,
                            out string error, string source = "Source", string dest = "ReSize")
        {
            string result = "";
            error = "";
            try
            {
                string url = ImageSite + "/ImageTool/ResizePicWithMap?type=" + type + "&name=" +
                                 name + FileSiteValidKey + "&x=" + x + "&y=" + y + "&width=" + width + "&height=" + height
                                 + "&widthZipRate=" + widthZipRate + "&heightZipRate=" + heightZipRate
                                 + "&targetWidth=" + targetWidth + "&targetHeight=" + targetHeight
                                 + "&mappedSource=" + mappedSource + "&source=" + source + "&dest=" + dest;

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                using (WebResponse rep = req.GetResponse())
                {
                    using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                req.Abort();
            }
            catch (Exception e)
            {
                error = e.Message;
                return "";
            }

            string errorFlag = "Error:";

            //返回有错误
            if (result.StartsWith(errorFlag))
            {
                error = result.Substring(errorFlag.Length - 1);
                result = "";
            }

            return result;
        }
        #endregion

        #region  上传文件到file.ymatou.com
        public static string UploadFile(HttpPostedFileBase postedFile, string fileType, string savedFileName, out string error, bool autoName = true, string source = "")
        {
            byte[] bt = new byte[postedFile.ContentLength];
            postedFile.InputStream.Read(bt, 0, bt.Length);
            postedFile.InputStream.Close();

            return UploadFile(bt, fileType, savedFileName, out error, autoName, source);
        }

        public static string UploadFile(Stream fileStream, string fileType, string savedFileName, out string error, bool autoName = true, string source = "")
        {
            byte[] bt = new byte[fileStream.Length];
            fileStream.Read(bt, 0, bt.Length);
            fileStream.Close();

            return UploadFile(bt, fileType, savedFileName, out error, autoName, source);
        }

        public static string UploadFile(byte[] bytes, string fileType, string savedFileName, out string error, bool autoName = true, string source = "")
        {
            if(!string.IsNullOrEmpty(savedFileName))
            {
                savedFileName = savedFileName.ToLower();
            }
            error = "";
            string result = "";
            try
            {
                string url = FileSite + "/BHUploadFile.ashx?fname=" + savedFileName + "&type="
                                +fileType + FileSiteValidKey + "&autoName=" + autoName;

                if (!string.IsNullOrEmpty(source))
                {
                    url += "&source=" + source;
                }

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                Stream requestStream = req.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                using (WebResponse rep = req.GetResponse())
                {
                    using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }

                req.Abort();
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return "";
            }

            string errorFlag = "Error:";

            //返回有错误
            if (result.StartsWith(errorFlag))
            {
                error = result.Substring(errorFlag.Length);
                result = "";
            }

            return result;
        }

        public static string GetPreviewPic(string type, string name, int maxWidth, int maxHeight, out string error, out int width, out int height, string source = "", string dest = "preview")
        {
            string result = "";
            error = "";
            width = 0;
            height = 0;
            try
            {
                string url = FileSite + "/action/GetPreviewPic?type=" + type + "&name=" +
                                 name + FileSiteValidKey + "&maxWidth=" + maxWidth + "&maxHeight=" + maxHeight
                                 + "&source=" + source + "&dest=" + dest;


                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                using (WebResponse rep = req.GetResponse())
                {
                    using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                req.Abort();
            }
            catch (Exception e)
            {
                error = e.Message;
                return "";
            }

            string errorFlag = "Error:";

            //返回有错误
            if (result.StartsWith(errorFlag))
            {
                error = result.Substring(errorFlag.Length - 1);
                result = "";
            }
            else
            {
                string param = result.Substring(result.LastIndexOf("#") + 1);
                int.TryParse(param.Split('&')[0], out width);
                int.TryParse(param.Split('&')[1], out height);
            }

            return result.Substring(0, result.LastIndexOf("#"));
        }

        public static string AddWaterMark(string type, string name, string fmark, out string error, string source = "", string dest = "")
        {
            string result = "";
            error = "";
            try
            {
                string url = FileSite + "/action/AddWaterMark?type=" + type + "&name=" +
                                 name + FileSiteValidKey + "&fmark=" + fmark
                                 + "&source=" + source + "&dest=" + dest;


                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                using (WebResponse rep = req.GetResponse())
                {
                    using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                req.Abort();
            }
            catch (Exception e)
            {
                error = e.Message;
                return "";
            }

            string errorFlag = "Error:";

            //返回有错误
            if (result.StartsWith(errorFlag))
            {
                error = result.Substring(errorFlag.Length - 1);
                result = "";
            }

            return result;
        }

        public static bool DeleteFile(string name, string type, out string error, string source = "")
        {
            string result = "";
            error = "";
            try
            {
                string url = FileSite + "/action/DeleteFile?type=" + type + "&name=" +
                             name + FileSiteValidKey + "&source=" + source;


                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                using (WebResponse rep = req.GetResponse())
                {
                    using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                req.Abort();
            }
            catch (Exception e)
            {
                error = e.Message;
                return false;
            }

            string errorFlag = "Error:";

            //返回有错误
            if (result.StartsWith(errorFlag))
            {
                error = result.Substring(errorFlag.Length - 1);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="name"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="widthZipRate"></param>
        /// <param name="heightZipRate"></param>
        /// <param name="mappedSource">源图片</param>
        /// <param name="error"></param>
        /// <param name="source">现在处理的预览图</param>
        /// <param name="dest">处理后图片的位置</param>
        /// <returns></returns>
        public static string ResizePic(string type, string name, float x, float y, float width, float height,
                        float widthZipRate, float heightZipRate, string mappedSource, int targetWidth, int targetHeight,
                            out string error, string source = "", string dest = "resize")
        {
            string result = "";
            error = "";
            try
            {
                string url = FileSite + "/action/ResizePicWithMap?type=" + type + "&name=" +
                                 name + FileSiteValidKey + "&x=" + x + "&y=" + y + "&width=" + width + "&height=" + height
                                 + "&widthZipRate=" + widthZipRate + "&heightZipRate=" + heightZipRate
                                 + "&targetWidth=" + targetWidth + "&targetHeight=" + targetHeight
                                 + "&mappedSource=" + mappedSource + "&source=" + source + "&dest=" + dest;

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                using (WebResponse rep = req.GetResponse())
                {
                    using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                req.Abort();
            }
            catch (Exception e)
            {
                error = e.Message;
                return "";
            }

            string errorFlag = "Error:";

            //返回有错误
            if (result.StartsWith(errorFlag))
            {
                error = result.Substring(errorFlag.Length - 1);
                result = "";
            }

            return result;
        }


        /// <summary>
        /// 将网页生成pdf
        /// </summary>
        public static string CreatePdfFileFromHtml(string pageUrl, string type, out string error, bool autoName = true, string fileName = "")
        {
            if(!string.IsNullOrEmpty(pageUrl))
            {
                pageUrl = Microsoft.JScript.GlobalObject.escape(pageUrl);
            }

            string result = "";
            error = "";
            try
            {
                string url = FileSite + "/action/CreatePdfFromUrl?url=" + pageUrl + "&type=" + type + "&autoName=" +
                             autoName + FileSiteValidKey + "&fileName=" + fileName;


                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                using (WebResponse rep = req.GetResponse())
                {
                    using (var sr = new StreamReader(rep.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                req.Abort();
            }
            catch (Exception e)
            {
                error = e.Message;
                return string.Empty;
            }

            string errorFlag = "Error:";

            //返回有错误
            if (result.StartsWith(errorFlag))
            {
                error = result.Substring(errorFlag.Length - 1);
                return string.Empty;
            }

            return result;
        }

        public static byte[] DownloadFile(string url, out string contentType, out string error)
        {
            byte[] file = null;
            contentType = string.Empty;
            error = string.Empty;
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                //req.ContentType = "application/x-www-form-urlencoded";
                using (WebResponse rep = req.GetResponse())
                {
                    Stream s = rep.GetResponseStream();
                    contentType = rep.ContentType;
                    byte[] content = new byte[30000000];
                    int bufferlength = 1;
                    int size = 0;
                    while(bufferlength > 0)
                    {
                        bufferlength = s.Read(content, size, 1024);
                        size += bufferlength;
                    }
                    
                    file = new byte[size];
                    Buffer.BlockCopy(content, 0, file, 0, size);
                }

                req.Abort();
            }
            catch (Exception ex)
            {
                error = ex.Message.ToString();
            }

            return file;
        }

        #endregion
    }
}
